import {
    AxiosResponse
} from 'axios';

import {
    DataRes,
    RequestConfig
} from './../types';

import {
    instance
} from './../index';

import * as Token from './../token';

import * as lag from '../headers/lag';

const reSend = (para:any) => (
    instance(para)
)

const _default = async (res: AxiosResponse): Promise<any>=> {
    const {
        config,
        headers,
        data: _data
    } = res;

    const {
        timestamp
    } = headers;

    const {
        code,
        data
    } = _data as DataRes;

    const {
        reSendPara
    } = config as RequestConfig;

    switch (code) {
        case 200 : {
            return Promise.resolve(data)
        }
        //token过期
        case 10011 : {
            await Token.refresh();
            return reSend(reSendPara);
        }
        //时间不一致
        case 10020 : {
            const _now = Date.now();
            await lag.setTime(_now - timestamp);
            return reSend(reSendPara);
        }
        //登录失效
        case 30001001 : {
            Token.unLogin();
        }
        case 10103:{
            Token.unLogin();
        }
        case 31001:{
            Token.unLogin();
        }
        default : {
            return Promise.reject(_data);
        }
    }
}

export default _default;

